package com.neusoft.config;

import com.neusoft.exception.AuthFailException;
import com.neusoft.mapper.EmpMapper;
import com.neusoft.model.Emp;
import com.neusoft.utils.EmpUtil;
import com.neusoft.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author cpx
 * @date 2024/9/28
 * @Description
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    EmpMapper empMapper;

    private void throwAuthFailedException() throws AuthFailException {
        throw new AuthFailException(403,"auth failed");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                System.out.println("preHandle");
        //获取token
        String token = request.getHeader("Authorization");

        System.out.println(request.getHeader("Authorization")+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        try{
            if(token != null){
                String userId = null;
                System.out.println("token不为空");
                if(tokenUtil.validateToken(token))
                {
                    System.out.println("token有效");
                    //解析token获取用户id
                    userId = tokenUtil.getSub(token);
                    Emp emp = empMapper.selectById(userId);
                    System.out.println(emp.getEmpname());
                    //save
                    EmpUtil.setLoginEmp(emp); //为当前的线程变量赋值上用户信息
                    System.out.println("放行");
                    return true;
                }
                else{
                    //token过期无效
                    throwAuthFailedException();
                    return false;
                }
            }
            else{
                //token为空
                System.out.println("token为空");
                throwAuthFailedException();
                return false;
            }
        }
        catch (Exception e){
            //
            throwAuthFailedException();
            return false;
        }
        finally {
            System.out.println("finally");
        }
//        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
        EmpUtil.removeEmp();
    }
}
